package com.company.Nio.chat;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

public class ChatServer {

    private ServerSocketChannel listenerChannel;//监听通道 老大
    private Selector selector;//选择器对象
    private static final int PORT = 9999;//端口

    public ChatServer() {
        try {
            //得到监听通道
            listenerChannel = ServerSocketChannel.open();
            //得到选择器
            selector = Selector.open();
            //绑定端口
            listenerChannel.bind(new InetSocketAddress(PORT));
            //设置非阻塞
            listenerChannel.configureBlocking(false);
            //注册到选择器
            listenerChannel.register(selector, SelectionKey.OP_ACCEPT);
            printInfo("Chat Server is ready.......");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //干活
    public void start() {
        try {
            while (true) {
                if (selector.select(2000) == 0) {
                    System.out.println("没有客户端连接,服务端干别的事");
                    continue;
                }

                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isAcceptable()) {
                        SocketChannel sc = listenerChannel.accept();
                        sc.configureBlocking(false);
                        sc.register(selector, SelectionKey.OP_READ);//
                        printInfo(sc.getRemoteAddress().toString().substring(1) + "上线了!"); //得到远程的地址
                    }
                    if (key.isReadable()) {
                        readMsg(key);
                    }
                    //处理完毕删除key
                    iterator.remove();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取客户端发来的数据并广播出去
     *
     * @param key
     */
    public void readMsg(SelectionKey key) throws Exception {
        SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int count = channel.read(buffer);
        if (count > 0) {//读到数据
            String msg = new String(buffer.array());
            printInfo(msg);
            //发广播
            broadCast(channel, msg);
        }

    }

    //给所有客户端发广播
    public void broadCast(SocketChannel except, String msg) throws Exception {
        System.err.println("服务器发送的广播...");
        //所有就绪的key
        for (SelectionKey key : selector.keys()) {//给其他人发广播
            Channel targetChannel = key.channel();
            if (targetChannel instanceof SocketChannel && targetChannel != except) {//排除自身
                SocketChannel destChannel = (SocketChannel) targetChannel;
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                destChannel.write(buffer);
            }
        }

    }

    private void printInfo(String str) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("[" + sdf.format(new Date()) + "] ->" + str);
    }

    public static void main(String[] args) {
        new ChatServer().start();

    }


}
